package tr.edu.ege.kipler.syntax;

import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author İnanç Seylan
 *
 */
public class NameManager {
	private static NameManager instance;

	private NameManager() {

	}

	public static NameManager getInstance() {
		if (instance == null) {
			instance = new NameManager();
		}
		return instance;
	}

	private Map<String, String> prefixUriMap = new HashMap<String, String>();

	private Map<String, String> uriPrefixMap = new HashMap<String, String>();

	private Map<String, Name> uriNameMap = new HashMap<String, Name>();

	public Name getName(String absoluteURI) {
		Name result;
		if (uriNameMap.containsKey(absoluteURI)) {
			result = uriNameMap.get(absoluteURI);
		} else {
			result = new Name();
			result.setUri(absoluteURI);
			uriNameMap.put(absoluteURI, result);
		}
		return result;
	}

	public void addPrefix(String prefix, String uri) {
		prefixUriMap.put(prefix, uri);
		uriPrefixMap.put(uri, prefix);
	}

	public String getURI(String prefix) {
		return prefixUriMap.get(prefix);
	}

	public String getPrefix(String uri) {
		return uriPrefixMap.get(uri);
	}

	public String toQname(String uri) {
		String result = null;
		String url = getUrl(uri);
		if (url == "") { // not a valid url
			result = uri;
		} else {
			result = "<" + uri + ">";
			if (uriPrefixMap.containsKey(url + "#")) {
				result = getPrefix(url + "#") + ":" + getLocalName(uri);
			}
		}
		return result;
	}

	public static String getUrl(String uri) {
		String result = "";
		int i = uri.indexOf("#");
		if (i != -1)
			result = uri.substring(0, i);
		return result;
	}

	public static String getLocalName(String uri) {
		int i = uri.indexOf("#");
		return uri.substring(i + 1);
	}

}
